const {
	Service
} = require('uni-cloud-router')

const {
	wxapi,
	utils
} = require('use-api');

const crypto = require('crypto');

module.exports = class H5wxService extends Service {

	constructor(ctx) {
		super(ctx)

		this.appid = wxapi.appid;
		this.message_notify_enabled = wxapi.message_notify_enabled;
	}

	/**
	 * access_token 是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token
	 * 
	 * access_token 的有效期目前为2个小时
	 */
	async get_access_token() {
		const token = await wxapi.get_token();

		return token;
	}

	/**
	 * 获取JSSDK signature
	 */
	async get_jssdk_signature(req) {
		// jsapi_ticket 是公众号用于调用微信 JS 接口的临时票据
		req.jsapi_ticket = await wxapi.get_jsapi_ticket();

		const keys = Object.keys(req).sort();
		const arr = [];
		keys.forEach(k => {
			arr.push(`${k}=${req[k]}`);
		});

		const str = arr.join('&');
		console.log('sha1 str', str);
		const sign = this.sha1(str);

		return sign;
	}

	/**
	 * sha1加密
	 **/
	sha1(str) {
		const shasum = crypto.createHash("sha1");
		shasum.update(str);

		str = shasum.digest("hex");

		return str
	}

}
